package cn.stylefeng.guns.core.util;


import cn.stylefeng.roses.core.util.ToolUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class StringUtil {




	private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };



	/**
	 * 判断2个字符串是否相等
	 * @param a
	 * @param b
	 * @return
	 */
	public static boolean equal(String a,String b){
		boolean result = false;
		if(null==a||""==a){
			if(null==b||""==b){
				result=true;
			}
		}else{
			if(null!=b&&a.trim().equals(b.trim())){
				result=true; 
			}
		}
		return result;
	}
	
	/**
	 * 转码
	 * @return
	 */
    public static final String changeCode(String str, int unicodeFlag) {
        try {
            switch (unicodeFlag) {
            case 0:
                return str;
            case 1:
                return new String(str.getBytes("ISO-8859-1"), "gb2312");
            case 2:
                return new String(str.getBytes("gb2312"), "ISO-8859-1");
            case 3:
                return new String(str.getBytes("UTF-8"), "gb2312");
            case 4:
                return new String(str.getBytes("gb2312"), "UTF-8");
            case 5:
                return new String(str.getBytes("GBK"), "ISO-8859-1");
            case 6:
                return new String(str.getBytes("ISO-8859-1"), "GBK");                    
            default:
                return str;
            }
        } catch (Exception ex) {
            return "";
        }
    }
    
	/**
	 * 转码2
	 * @return
	 */
    public static String getString(String s, String srcEncoding, String destEncoding) {
        try {
            return new String(s.getBytes(srcEncoding), destEncoding);
        } catch (UnsupportedEncodingException e) {
            return s;
        }
    }
    
	/**
	 * 前面补零
	 * @param
	 * @param
	 * @return
	 */
	public static String front(String str,int lenght){
		
		for(;str.length()<lenght;)
		{
			str="0"+str;
		}
		return str;
	}
	
	/**
	 * 后面补零
	 * @param
	 * @param
	 * @return
	 */
	public static String back(String str,int lenght){
		
		for(;str.length()<lenght;)
		{
			str=str+"0";
		}
		return str;
	}
	
	

	
	public static String nullTo(Object o){
		if(o==null)
			return "";
		return o.toString().trim();
	}

	/**
	 * 获取该天得最后时刻
	 * @param date
	 * @return
	 * @throws ParseException
	 */
	public static Date getEndDate(Date date) throws ParseException{
		SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
		String dd;
		try {
			dd = myFormatter.format(date);
		} catch (Exception e) {
			dd = myFormatter.format(new Date());
		}
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		return format.parse(dd + " 23:59:59");
	}
	
	/**
	 * 获取该天开始时间
	 * @param date
	 * @return
	 * @throws ParseException
	 */
	public static Date getStartDate(Date date) throws ParseException{
		SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
		String dd;
		try {
			dd = myFormatter.format(date);
		} catch (Exception e) {
			dd = myFormatter.format(new Date());
		}
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		return format.parse(dd + " 00:00:00");
	}
	
	/**
	 * 
	 * @param sku  SKU编号
	 * @param sequence  序列  1.商品主键 2.颜色 3.尺寸
	 * @return
	 */
	public static Integer getIdForSku(String sku ,int sequence) {
	     String tmp=""; 
		 if(sku!=null){
		     if(sequence==1){
		    	 tmp= sku.substring(2,10);
		     }else if(sequence==2){
		    	 tmp= sku.substring(10,15);
		     }else if(sequence==3){
		    	 tmp= sku.substring(15,20);
		     }
		 }
	     if(!"".equals(toRemoveBeforeChar(tmp,"0"))){
	    	 return Integer.valueOf(toRemoveBeforeChar(tmp,"0"));
	     }else{
	    	 return 0;
	     }
		
		 
	}
	
	/***
	 * 移除某字符前的字符
	 * @param str  原字符串  "00010034"
	 * @param character  字符  "0"
	 * @return 移除字符后的字符串  "10034"
	 */
	public static String toRemoveBeforeChar(String str ,String character){
		String tmp ="" ;
		if(str!=null){
			for(int i=0;i<str.length();i++){
				   if(!character.equals(String.valueOf(str.charAt(i)))){
				    	tmp  = str.substring(i, str.length());
				    	break;
				    } 
			}
		}
		return tmp ;
	}

	// 将request中的参数转换成Map
	public static Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
		Map<String, String> retMap = new HashMap<String, String>();
		Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();
		for (Map.Entry<String, String[]> entry : entrySet) {
			String name = entry.getKey();
			String[] values = entry.getValue();
			int valLen = values.length;
			if (valLen == 1) {
				retMap.put(name, values[0]);
			} else if (valLen > 1) {
				StringBuilder sb = new StringBuilder();
				for (String val : values) {
					sb.append(",").append(val);
				}
				retMap.put(name, sb.toString().substring(1));
			} else {
				retMap.put(name, "");
			}
		}
		return retMap;
	}

	/**
	 * 产生6位随机数(000000-999999)	 * 	 * @return 6位随机数
	 */
	public static String getFourRandom() {
		Random random = new Random();
		String fourRandom = random.nextInt(1000000) + "";
		int randLength = fourRandom.length();
		if (randLength < 6) {
			for (int i = 1; i <= 6 - randLength; i++)
				fourRandom = "0" + fourRandom;
		}
		return fourRandom;
	}

	/**
	 *  判断日期是星期几
	 * @return
	 */
	public static String dayForWeek(LocalDate currentDate) {
		String[][] strArray ={{"MONDAY","一"},{"TUESDAY","二"},{"WEDNESDAY","三"},
				{"THURSDAY","四"},{"FRIDAY","五"},{"SATURDAY","六"},{"SUNDAY","日"}};
		//LocalDate currentDate = LocalDate.now();
		String k = String.valueOf(currentDate.getDayOfWeek());
		//获取行数
		for (int i = 0; i < strArray.length; i++) {
			if (k.equals(strArray[i][0])) {
				k = strArray[i][1];
				break;
			}
		}
		System.out.println("星期" + k);
		return "星期" + k;
	}

	/**
	 * 获取文件名
	 * 只适用于腾讯云对象存储
	 */
	public static String getFileName(String filePath){
		String[] split = filePath.split("/");
		return split[split.length - 1];
	}


	/**
	 * 获取对象中为null的属性
	 * @param source
	 * @return
	 */
	public static String[] getNullPropertyNames (Object source) {
		final BeanWrapper src = new BeanWrapperImpl(source);
		java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

		Set<String> emptyNames = new HashSet<String>();
		for(java.beans.PropertyDescriptor pd : pds) {
			Object srcValue = src.getPropertyValue(pd.getName());
			if (srcValue == null) emptyNames.add(pd.getName());
		}
		String[] result = new String[emptyNames.size()];
		return emptyNames.toArray(result);
	}

	/**
	 * Spring 的BeanUtils.copyProperties在拷贝属性时忽略空值
	 * @param src
	 * @param target
	 */
	public static void copyPropertiesIgnoreNull(Object src, Object target){
		BeanUtils.copyProperties(src, target, getNullPropertyNames(src));
	}

	public static String getFormattedText(byte[] bytes) {
		int len = bytes.length;
		StringBuilder buf = new StringBuilder(len * 2);
		// 把密文转换成十六进制的字符串形式
		for (int j = 0; j < len; j++) {
			buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
			buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
		}
		return buf.toString();
	}

	public static Boolean isLinux (){
		String os = System.getProperty("os.name");
		if(os.toLowerCase().startsWith("win")){
			System.out.println(os + " can't gunzip");
			return false;
		}
		return true;
	}

	public static Map<String,Object> stringDifference (String str1, String str2){
		Map<String,Object> map = new HashMap<>();
		List<String> list1 = new ArrayList<>();
		String[] split1 = str1.split(",");
		for (int i = 0; i < split1.length; i++) {
			if(str2.indexOf(split1[i]) == -1){
				list1.add(split1[i]);
			}
		}
		List<String> list2 = new ArrayList<>();
		String[] split2 = str2.split(",");
		for (int i = 0; i < split2.length; i++) {
			if(str1.indexOf(split2[i]) == -1){
				list2.add(split2[i]);
			}
		}
		map.put("str1",list1);
		map.put("str2",list2);
		return map;
	}

	public static String[] strSplit (String str){
		return ToolUtil.isNotEmpty(str)?str.split(","):null;
	}

	public static void main(String[] args) {
		 isLinux ();
	}
}
